package com.futvan.z.framework.common.action;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.MenuTree;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.system.zcode.z_code;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zreport.z_report_column;
import com.futvan.z.system.zform.z_form_table_column;
import com.futvan.z.system.zuser.z_user;
import com.futvan.z.system.zvcode.z_vcode;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.HttpUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.SmsUtil;
import com.futvan.z.framework.util.SpringUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;


@Controller
public class CommonAction extends SuperAction{
	@Autowired
	private CommonService commonService;

	/**
	 * 	默认首页
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/default_index")
	public ModelAndView default_index() throws Exception {
		//添加系统常用参数
		request.getSession().setAttribute("sp", z.sp);

		//获取默认首页地址
		String default_index = z.sp.get("default_index");
		if(z.isNull(default_index)) {
			ModelAndView  model = new ModelAndView("forward:web/login");
			return model;
		}else {
			ModelAndView  model = new ModelAndView("forward:"+default_index);
			return model;
		}
	}





	/**
	 * 管理系统登录页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/login")
	public ModelAndView login(String user_id,String UserLoginAlert) throws Exception {
		String ViewName = "common/main/login";
		//判读是否是手机访问
		if(isMobile()) {
			ViewName = ViewName + "_mobile";
		}
		ModelAndView model = new ModelAndView(ViewName);
		//添加系统常用参数
		request.getSession().setAttribute("sp", z.sp);
		if(z.isNotNull(user_id)) {
			model.addObject("user_id", user_id);
		}
		if(z.isNotNull(UserLoginAlert)) {
			model.addObject("UserLoginAlert", java.net.URLDecoder.decode(UserLoginAlert,"UTF-8"));
		}
		return model;
	}

	@RequestMapping(value="/main_index")
	public String main_index() throws Exception {
		return "common/main/main_index";
	}


	/**
	 * 管理员登陆
	 * @param z_username
	 * @param z_password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/UserLogin")
	public ModelAndView UserLogin(@RequestParam HashMap<String,String> bean) throws Exception {
		String user_id = bean.get("user_id");
		String password = bean.get("password");
		String orgid = bean.get("orgid");
		if(z.isNotNull(user_id)) {
			//从数据库中查询登录用户信息
			z_user db_user = GetDBUser(user_id);
			if(db_user!=null) {
				if((!"".equals(orgid) && orgid!=null) || user_id.equals(z.sp.get("super_user"))) {
					if("1".equals(db_user.getIs_start()) || user_id.equals(z.sp.get("super_user"))) {
						if(!"".equals(db_user.getLogin_password()) && db_user.getLogin_password()!=null) {
							String jia_password = StringUtil.CreatePassword(password);
							if(jia_password.equals(db_user.getLogin_password())) {
								ModelAndView  model = new ModelAndView("redirect:/main");
								SetSessionUser(request, db_user,orgid);
								return model;
							}else {
								ModelAndView  model = new ModelAndView("redirect:/login");
								model.addObject("UserLoginAlert",java.net.URLEncoder.encode("密码错误","UTF-8"));
								model.addObject("user_id", user_id);
								return model;
							}
						}else {
							ModelAndView  model = new ModelAndView("redirect:/login");
							model.addObject("UserLoginAlert",java.net.URLEncoder.encode("用户未设置登陆密码","UTF-8"));
							model.addObject("user_id", user_id);
							return model;
						}
					}else {
						ModelAndView  model = new ModelAndView("redirect:/login");
						model.addObject("UserLoginAlert", java.net.URLEncoder.encode("该用户未启用","UTF-8"));
						model.addObject("user_id", user_id);
						return model;
					}
				}else {
					ModelAndView  model = new ModelAndView("redirect:/login");
					model.addObject("UserLoginAlert", java.net.URLEncoder.encode("账号未分配所属部门","UTF-8"));
					model.addObject("user_id", user_id);
					return model;
				}

			}else {
				ModelAndView  model = new ModelAndView("redirect:/login");
				model.addObject("UserLoginAlert", java.net.URLEncoder.encode("无此用户","UTF-8"));
				model.addObject("user_id", user_id);
				return model;
			}
		}else {
			ModelAndView  model = new ModelAndView("redirect:/login");
			model.addObject("UserLoginAlert", java.net.URLEncoder.encode("用户账号不可为空","UTF-8"));
			return model;
		}
	}

	/**
	 * 管理员登陆
	 * @param z_username
	 * @param z_password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/UserLoginJson")
	public @ResponseBody Result UserLoginJson(String user_id,String password,String orgid) throws Exception {
		Result result = new Result();
		z_user db_user = GetDBUser(user_id);
		if(db_user!=null) {
			if((!"".equals(orgid) && orgid!=null) || user_id.equals(z.sp.get("super_user"))) {
				if("1".equals(db_user.getIs_start()) || user_id.equals(z.sp.get("super_user"))) {
					if(!"".equals(db_user.getLogin_password()) && db_user.getLogin_password()!=null) {
						String jia_password = StringUtil.CreatePassword(password);
						if(jia_password.equals(db_user.getLogin_password())) {
							//添加到在线用户中
							SetSessionUser(request, db_user,orgid);
							result.setCode(Code.SUCCESS);
							result.setMsg("登录成功");
							Map info = new HashMap();
							info.put("user", db_user);
							info.put("org", z.orgs.get(orgid));
							result.setData(info);
						}else {
							result.setCode(Code.ERROR);
							result.setMsg("密码错误");
						}
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("用户未设置登陆密码");
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("该用户未启用");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("账号未分配所属部门");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("无此用户");
		}
		return result;
	}

	@RequestMapping(value="/UserExit")
	public ModelAndView UserExit() throws Exception {

		//删除Session中用户信息
		request.getSession().removeAttribute("zuser");

		//删除在线用户表记录
		DeleteSessionUser(request.getSession().getId());

		//跳转到登陆页面
		ModelAndView  model = new ModelAndView("redirect:/login");
		return model;
	}

	/**
	 * 管理系统主页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/main")
	public ModelAndView main() throws Exception {
		String ViewName = "common/main/main";
		//判读是否是手机访问
		if(isMobile()) {
			ViewName = ViewName + "_mobile";
		}
		ModelAndView model = new ModelAndView(ViewName);

		//手机端获取代办任务
		if(isMobile()) {
			model.addObject("workjobList", commonService.getWorkjobList(GetSessionUserId()));
		}

		//获取菜单
		String userId = GetSessionUserId(request);
		model.addObject("menuTreeList", commonService.getSystemMenuTree(userId,request));

		return model;
	}

	/**
	 * 手机端的用户中心
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/user_center_mobile")
	public ModelAndView user_center_mobile() throws Exception {
		ModelAndView model = new ModelAndView("common/main/user_center_mobile");
		//获取用户信息
		String userId = GetSessionUserId(request);
		return model;
	}

	/**
	 * 手机端功能菜单页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/nav_mobile")
	public ModelAndView nav_mobile() throws Exception {
		ModelAndView model = new ModelAndView("common/main/nav_mobile");
		//获取菜单
		String userId = GetSessionUserId(request);
		model.addObject("menuTreeList", commonService.getSystemMenuTree(userId,request));
		return model;
	}

	@RequestMapping(value="/LoadParameter")
	public @ResponseBody Result LoadParameter() throws Exception{
		Result result = new Result();
		try {
			z.Log("更新系统参数:"+DateUtil.getDateTime());
			RLoadParameter();
			
			//添加系统常用参数
			request.getSession().setAttribute("sp", z.sp);
			
			result.setCode(Code.SUCCESS);
			result.setMsg("更新系统参数成功");
		} catch (Exception e) {
			String errorinfo = "更新系统参数出错:"+e.getMessage();
			z.Error(errorinfo, e);
			result.setCode(Code.ERROR);
			result.setMsg(errorinfo);
		}
		return result;
	}

	@RequestMapping(value="/error_404")
	public String error_404(HttpServletRequest request){
		return "common/error/404";
	}

	@RequestMapping(value="/rlist")
	public ModelAndView rlist(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.rlist(bean,"common/form/rlist",request);
	}

	@RequestMapping(value="/list")
	public ModelAndView list(@RequestParam HashMap<String,String> bean) throws Exception {
		z_form_table t = z.tables.get(bean.get("tableId"));
		if("list".equals(t.getList_action())) {
			return commonService.list(bean,"common/form/list",request);
		}else {
			//非标准查询事件
			ModelAndView redirect_mv = new ModelAndView("redirect:/"+t.getList_action());
			redirect_mv.addAllObjects(bean);
			return redirect_mv;
		}
	}

	/**
	 * 新增
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	public ModelAndView add(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.add("common/form/add",bean,request);
	}

	/**
	 * 修改
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.edit("common/form/edit",bean,request);
	}

	/**
	 * 打印列表
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/print_list")
	public @ResponseBody Result print_list(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.print_list(bean,request);
	}

	/**
	 * 查看
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/look")
	public ModelAndView look(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.edit("common/form/look",bean,request);
	}

	@RequestMapping(value="/addDetail")
	public ModelAndView addDetail(@RequestParam HashMap<String,String> bean) throws Exception {
		return commonService.add("common/form/add",bean,request);
	}

	@RequestMapping(value="/insert")
	public @ResponseBody Result insert(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.insert(bean,request);
	}

	@RequestMapping(value="/update")
	public @ResponseBody Result update(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.update(bean,request);
	}
	@RequestMapping(value="/updateForBean")
	public @ResponseBody Result updateForBean(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.updateForBean(bean,request);
	}

	@RequestMapping(value="/delete")
	public @ResponseBody Result delete(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.delete(bean,request);
	}

	/**
	 * 根据当前表Id获取上级表Id
	 * @param bean
	 * @return Code.SUCCESS Parent_table_id 或 Code.ERROR  
	 * @throws Exception
	 */
	@RequestMapping(value="/getParentTableId")
	public @ResponseBody Result getParentTableId(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		String tableId = bean.get("tableId");
		String Parent_table_id = z.tables.get(tableId).getParent_table_id();
		if(!"".equals(Parent_table_id) && Parent_table_id!=null) {
			result.setCode(Code.SUCCESS);
			result.setData(Parent_table_id);
		}else {
			result.setCode(Code.ERROR);
		}
		return result;
	}

	@RequestMapping(value="/Z5list")
	public ModelAndView Z5list(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.getZ5List(bean);
	}

	@RequestMapping(value="/openUploadFile")
	public ModelAndView openUploadFile(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		ModelAndView model = new ModelAndView("common/form/fileUpload");
		model.addObject("bean", bean);
		return model;
	}

	/**
	 * 根据CodeId获取Code对象
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getCodeJson",method=RequestMethod.GET)
	public @ResponseBody Result getCodeJson(String CodeId) throws Exception {
		Result result = new Result();
		z_code c = z.code.get(CodeId);
		if(c!=null && c.getZ_code_detail_list()!=null &&c.getZ_code_detail_list().size()>0) {
			result.setCode(Code.SUCCESS);
			result.setData(c);
		}else {
			result.setCode(Code.ERROR);
			result.setData("未查询到Code对象");
		}
		return result;
	}

	@RequestMapping(value="/Z5DesplayValueJson",method=RequestMethod.GET)
	public @ResponseBody Result Z5DesplayValueJson(String tableId,String tdColumnId,String tdColumnValue) throws Exception {
		Result result = new Result();
		if(z.isNotNull(tableId) && z.isNotNull(tdColumnId)) {
			String DisplayValue = z.Z5DisplayValue.get(tableId+"_"+tdColumnValue);
			if(!"".equals(DisplayValue) && DisplayValue!=null) {
				result.setCode(Code.SUCCESS);
				result.setData(DisplayValue);
			}else {
				z_form_table_column column = z.columns.get(tableId+"_"+tdColumnId);
				if(z.isNotNull(column.getZ5_table()) && z.isNotNull(column.getZ5_key())) {
					String sql = "select "+column.getZ5_value() +" from "+column.getZ5_table()+" where "+column.getZ5_key() +" = '"+tdColumnValue+"'";
					List<String> list = z.getSqlSession().selectList("selectone", sql);
					String DValue = "";
					if(list.size()>0) {
						DValue = list.get(0);
						z.Z5DisplayValue.put(tableId+"_"+tdColumnId, DValue);
					}
					result.setCode(Code.SUCCESS);
					result.setData(DValue);
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("未设置Z5字段参数");
				}
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("tableId/tdColumnId is not null");
		}

		return result;
	}


	@RequestMapping(value="/Z5DesplayValueJsonR",method=RequestMethod.GET)
	public @ResponseBody Result Z5DesplayValueJsonR(String reportid,String tdColumnId,String tdColumnValue) throws Exception {
		Result result = new Result();
		if(z.isNotNull(reportid) && z.isNotNull(tdColumnId)) {
			String DisplayValue = z.Z5DisplayValue.get(reportid+"_"+tdColumnValue);
			if(!"".equals(DisplayValue) && DisplayValue!=null) {
				result.setCode(Code.SUCCESS);
				result.setData(DisplayValue);
			}else {
				z_report_column column = z.reportColumns.get(reportid+"_"+tdColumnId);
				if(z.isNotNull(column.getZ5_table()) && z.isNotNull(column.getZ5_key())) {
					String sql = "select "+column.getZ5_value() +" from "+column.getZ5_table()+" where "+column.getZ5_key() +" = '"+tdColumnValue+"'";
					List<String> list = z.getSqlSession().selectList("selectone", sql);
					String DValue = "";
					if(list.size()>0) {
						DValue = list.get(0);
						z.Z5DisplayValue.put(reportid+"_"+tdColumnId, DValue);
					}
					result.setCode(Code.SUCCESS);
					result.setData(DValue);
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("报表中未设置Z5字段参数");
				}
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("reportid/tdColumnId is not null");
		}

		return result;
	}



	/**
	 *	生成自定义源码目录与文件
	 * @param CodeId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/CreateCodeingPath")
	public @ResponseBody Result CreateCodeingPath(String formId) throws Exception {
		Result result = new Result();
		//获取工程路径
		String project_path = z.sp.get("project_path");
		if(!"".equals(project_path) && project_path!=null) {
			//获取项目ID
			String project_id = z.formidToProjects.get(formId);
			if(!"".equals(project_id) && project_id!=null) {
				//生成Path
				CreatePathFile(project_path,formId,project_id);
				//生成Action
				CreateActionFile(project_path,formId,project_id);
				//生成Service
				CreateServiceFile(project_path,formId,project_id);
				//生成Bean
				CreateBeanFile(project_path,formId,project_id);
				//生成SQL
				CreateSQLFile(project_path,formId,project_id);
				result.setCode(Code.SUCCESS);

			}else {
				result.setCode(Code.ERROR);
				result.setData("project_id is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setData("project_path is null");
		}
		return result;
	}


	private void CreateBeanFile(String project_path, String formId, String project_id) throws Exception{

		//根据formId获取所有列名
		List<z_form_table> tableList = commonService.getTableList(formId);
		for (z_form_table table : tableList) {
			//根据路径获取加载文件
			String formIdUpper = table.getTable_id();//大写
			File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\"+project_id+"\\"+formId+"\\"+formIdUpper+".java");
			//如果找到文件删除
			if (f.exists()) {
				f.delete();
			}else{
				if (!f.getParentFile().exists()){
					f.getParentFile().mkdirs();
				}
			}
			//创建文件
			f.createNewFile();

			//创建输入流
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write("package com.futvan.z."+project_id+"."+formId+";\n");
			writer.write("import com.futvan.z.framework.core.SuperBean;\n");
			writer.write("import java.util.List;\n");
			writer.write("public class "+formIdUpper+" extends SuperBean{\n");
			//获取字段
			List<z_form_table_column> columnList = z.tables.get(table.getTable_id()).getZ_form_table_column_list();
			for (z_form_table_column column : columnList) {
				if(!"zid".equals(column.getColumn_id())
						&& !"number".equals(column.getColumn_id())
						&& !"name".equals(column.getColumn_id())
						&& !"seq".equals(column.getColumn_id())
						&& !"pid".equals(column.getColumn_id())
						&& !"create_user".equals(column.getColumn_id())
						&& !"create_time".equals(column.getColumn_id())
						&& !"update_user".equals(column.getColumn_id())
						&& !"update_time".equals(column.getColumn_id())
						&& !"zversion".equals(column.getColumn_id())
						&& !"orgid".equals(column.getColumn_id())
						&& !"remarks".equals(column.getColumn_id())){
					//获取表字段
					writer.write("	//"+column.getColumn_name()+"\n");
					writer.write("	private String "+column.getColumn_id()+";\n");
					writer.newLine();
				}

			}

			//生成明细表字段
			List<z_form_table> detailList = z.tables.get(table.getTable_id()).getZ_form_table_detail_list();
			for (z_form_table dTable : detailList) {
				writer.write("	//"+dTable.getTable_title()+"\n");
				writer.write("	private List<"+dTable.getTable_id()+"> "+dTable.getTable_id()+"_list;\n");
				writer.newLine();
			}

			//生成get set方法
			for (z_form_table_column column : columnList) {
				if(!"zid".equals(column.getColumn_id())
						&& !"number".equals(column.getColumn_id())
						&& !"name".equals(column.getColumn_id())
						&& !"seq".equals(column.getColumn_id())
						&& !"pid".equals(column.getColumn_id())
						&& !"create_user".equals(column.getColumn_id())
						&& !"create_time".equals(column.getColumn_id())
						&& !"update_user".equals(column.getColumn_id())
						&& !"update_time".equals(column.getColumn_id())
						&& !"zversion".equals(column.getColumn_id())
						&& !"orgid".equals(column.getColumn_id())
						&& !"remarks".equals(column.getColumn_id())){
					//生成get方法
					writer.write("	/**\n");
					writer.write("	* get"+column.getColumn_name()+"\n");
					writer.write("	* @return "+column.getColumn_id()+"\n");
					writer.write("	*/\n");
					writer.write("	public String get"+StringUtil.firstLetterToUpper(column.getColumn_id())+"() {\n");
					writer.write("		return "+column.getColumn_id()+";\n");
					writer.write("  	}\n");
					writer.newLine();

					//生成set方法
					writer.write("	/**\n");
					writer.write("	* set"+column.getColumn_name()+"\n");
					writer.write("	* @return "+column.getColumn_id()+"\n");
					writer.write("	*/\n");
					writer.write("	public void set"+StringUtil.firstLetterToUpper(column.getColumn_id())+"(String "+column.getColumn_id()+") {\n");
					writer.write("		this."+column.getColumn_id()+" = "+column.getColumn_id()+";\n");
					writer.write(" 	}\n");
					writer.newLine();
				}

			}

			//生成明细表get set方法
			for (z_form_table dTable : detailList) {
				//生成get方法
				writer.write("	/**\n");
				writer.write("	* get"+dTable.getTable_title()+"\n");
				writer.write("	* @return "+dTable.getTable_title()+"\n");
				writer.write("	*/\n");
				writer.write("	public List<"+dTable.getTable_id()+"> get"+StringUtil.firstLetterToUpper(dTable.getTable_id())+"_list() {\n");
				writer.write("		return "+dTable.getTable_id()+"_list;\n");
				writer.write("  	}\n");
				writer.newLine();

				//生成set方法
				writer.write("	/**\n");
				writer.write("	* set"+dTable.getTable_title()+"\n");
				writer.write("	* @return "+dTable.getTable_title()+"\n");
				writer.write("	*/\n");
				writer.write("	public void set"+StringUtil.firstLetterToUpper(dTable.getTable_id())+"_list(List<"+dTable.getTable_id()+"> "+dTable.getTable_id()+"_list) {\n");
				writer.write("		this."+dTable.getTable_id()+"_list = "+dTable.getTable_id()+"_list;\n");
				writer.write(" 	}\n");
				writer.newLine();
			}

			writer.write("}\n");
			writer.close();
			write.close();

		}
	}

	private void CreateSQLFile(String project_path, String formId, String project_id) throws Exception{
		//根据路径获取加载文件
		String formIdUpper = StringUtil.firstLetterToUpper(formId);//大写
		String formIdLower = StringUtil.firstLetterToLower(formId);//小写
		File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\"+project_id+"\\"+formId+"\\"+formIdUpper+"SQL.xml");
		//如果找到文件删除
		if (f.exists()) {
			f.delete();
		}else{
			if (!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
		}
		//创建文件
		f.createNewFile();
		//创建输入流
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
		BufferedWriter writer = new BufferedWriter(write);
		writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		writer.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org/DTD Mapper 3.0\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
		writer.write("<mapper namespace=\""+formId+"\">\n");
		writer.newLine();
		//根据formId获取所有表
		List<z_form_table> tableList = commonService.getTableList(formId);
		for (z_form_table table : tableList) {
			//所有字段
			List<z_form_table_column> columnlist = z.tables.get(table.getTable_id()).getZ_form_table_column_list();
			//JavaBean文件
			String beanName = "com.futvan.z."+project_id+"."+formId+"."+table.getTable_id();

			//创建查询=======================================================================================================
			writer.write("	<select id=\""+table.getTable_id()+"_select\" parameterType=\""+beanName+"\" resultType=\""+beanName+"\">\n");
			writer.write("		select * from "+table.getTable_id()+" \n");
			writer.write("		<where>\n");
			//添加标准字段条件
			for (z_form_table_column column : columnlist) {
				writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
				if("0".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}else if("1".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" like #{"+column.getColumn_id()+"}\n");
				}else {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}
				writer.write("			</if>\n");
			}
			//添加其它条件
			writer.write("			<if test=\"sql_where_other != null\">\n");
			writer.write("				${sql_where_other} \n");
			writer.write("			</if>\n");
			writer.write("		</where>\n");
			//添加排序条件
			writer.write("		<if test=\"sql_order_by != null\">\n");
			writer.write("			order by ${sql_order_by} \n");
			writer.write("		</if>\n");
			writer.write("	</select>\n");
			writer.newLine();
			//创建查询select zid=======================================================================================================
			writer.write("	<select id=\""+table.getTable_id()+"_select_zid\" parameterType=\"java.lang.String\" resultType=\""+beanName+"\">\n");
			writer.write("		select * from "+table.getTable_id()+" where zid = #{zid} \n");
			writer.write("	</select>\n");
			writer.newLine();
			//创建查询select 自定义SQL=======================================================================================================
			writer.write("	<select id=\""+table.getTable_id()+"_select_sql\" parameterType=\"java.lang.String\" resultType=\""+beanName+"\">\n");
			writer.write("		<![CDATA[ ${_parameter} ]]> \n");
			writer.write("	</select>\n");
			writer.newLine();
			//创建查询select pid=======================================================================================================
			if(z.isNotNull(table.getParent_table_id())) {
				writer.write("	<select id=\""+table.getTable_id()+"_select_pid\" parameterType=\"java.lang.String\" resultType=\""+beanName+"\">\n");
				writer.write("		select * from "+table.getTable_id()+" where pid = #{pid} \n");
				writer.write("	</select>\n");
				writer.newLine();
			}
			//创建新增=======================================================================================================
			writer.write("	<insert id=\""+table.getTable_id()+"_insert\" parameterType=\""+beanName+"\">\n");
			writer.write("		insert into "+table.getTable_id()+"( \n");
			for (z_form_table_column column : columnlist) {
				if(!"zid".equals(column.getColumn_id())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				"+column.getColumn_id()+",\n");
					writer.write("			</if>\n");
				}
			}
			writer.write("				zid\n");
			writer.write("		)values( \n");
			for (z_form_table_column column : columnlist) {
				if(!"zid".equals(column.getColumn_id())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				#{"+column.getColumn_id()+"},\n");
					writer.write("			</if>\n");
				}
			}
			writer.write("				#{zid}\n");
			writer.write("		) \n");
			writer.write("	</insert>\n");
			writer.newLine();
			//创建修改=======================================================================================================
			writer.write("	<update id=\""+table.getTable_id()+"_update\" parameterType=\""+beanName+"\">\n");
			writer.write("		update "+table.getTable_id()+" \n");
			writer.write("		<set> \n");
			for (z_form_table_column column : columnlist) {
				if(!"zid".equals(column.getColumn_id())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				"+column.getColumn_id()+" = #{"+column.getColumn_id()+"},\n");
					writer.write("			</if>\n");
				}
			}
			writer.write("		</set> \n");
			writer.write("		<where>\n");
			//添加标准字段条件
			for (z_form_table_column column : columnlist) {
				writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
				if("0".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}else if("1".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" like #{"+column.getColumn_id()+"}\n");
				}else {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}
				writer.write("			</if>\n");
			}
			//添加其它条件
			writer.write("			<if test=\"sql_where_other != null\">\n");
			writer.write("				${sql_where_other} \n");
			writer.write("			</if>\n");
			writer.write("		</where>\n");
			writer.write("	</update>\n");
			writer.newLine();
			//创建修改=======================================================================================================
			writer.write("	<update id=\""+table.getTable_id()+"_update_zid\" parameterType=\""+beanName+"\">\n");
			writer.write("		update "+table.getTable_id()+" \n");
			writer.write("		<set> \n");
			for (z_form_table_column column : columnlist) {
				if(!"zid".equals(column.getColumn_id())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				"+column.getColumn_id()+" = #{"+column.getColumn_id()+"},\n");
					writer.write("			</if>\n");
				}
			}
			writer.write("		</set> \n");
			writer.write("		where zid = #{zid} \n");
			writer.write("	</update>\n");
			writer.newLine();
			//创建修改=======================================================================================================
			writer.write("	<update id=\""+table.getTable_id()+"_update_pid\" parameterType=\""+beanName+"\">\n");
			writer.write("		update "+table.getTable_id()+" \n");
			writer.write("		<set> \n");
			for (z_form_table_column column : columnlist) {
				if(!"zid".equals(column.getColumn_id()) && !"pid".equals(column.getColumn_id())) {
					writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
					writer.write("				"+column.getColumn_id()+" = #{"+column.getColumn_id()+"},\n");
					writer.write("			</if>\n");
				}
			}
			writer.write("		</set> \n");
			writer.write("		where pid = #{pid} \n");
			writer.write("	</update>\n");
			writer.newLine();
			//创建删除=======================================================================================================
			writer.write("	<delete id=\""+table.getTable_id()+"_delete\" parameterType=\""+beanName+"\">\n");
			writer.write("		delete from "+table.getTable_id()+" \n");
			writer.write("		<where>\n");
			//添加标准字段条件
			for (z_form_table_column column : columnlist) {
				writer.write("			<if test=\""+column.getColumn_id()+" != null\">\n");
				if("0".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}else if("1".equals(column.getCompare())) {
					writer.write("				and "+column.getColumn_id()+" like #{"+column.getColumn_id()+"}\n");
				}else {
					writer.write("				and "+column.getColumn_id()+" = #{"+column.getColumn_id()+"}\n");
				}
				writer.write("			</if>\n");
			}
			//添加其它条件
			writer.write("			<if test=\"sql_where_other != null\">\n");
			writer.write("				${sql_where_other} \n");
			writer.write("			</if>\n");
			writer.write("		</where>\n");
			writer.write("	</delete>\n");
			writer.newLine();
			//创建删除ForZid=======================================================================================================
			writer.write("	<delete id=\""+table.getTable_id()+"_delete_zid\" parameterType=\"java.lang.String\">\n");
			writer.write("		delete from "+table.getTable_id()+" where zid = #{zid} \n");
			writer.write("	</delete>\n");
			writer.newLine();
			//创建删除ForPid=======================================================================================================
			writer.write("	<delete id=\""+table.getTable_id()+"_delete_pid\" parameterType=\"java.lang.String\">\n");
			writer.write("		delete from "+table.getTable_id()+" where pid = #{pid} \n");
			writer.write("	</delete>\n");
			writer.newLine();
		}
		writer.write("</mapper>\n");
		writer.close();
		write.close();
	}
	private void CreateServiceFile(String project_path, String formId, String project_id) throws Exception{
		//根据路径获取加载文件
		String formIdUpper = StringUtil.firstLetterToUpper(formId);//大写
		String formIdLower = StringUtil.firstLetterToLower(formId);//小写
		File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\"+project_id+"\\"+formId+"\\"+formIdUpper+"Service.java");
		//如果未找到文件
		if (!f.exists()) {
			if (!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
			//创建文件
			f.createNewFile();
			//创建输入流
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write("package com.futvan.z."+project_id+"."+formId+";\n");
			writer.write("import org.springframework.stereotype.Service;\n");
			writer.write("import com.futvan.z.framework.core.SuperService;\n");
			writer.write("@Service\n");
			writer.write("public class "+formIdUpper+"Service extends SuperService{\n");
			writer.write("}\n");
			writer.close();
			write.close();
		}
	}
	private void CreateActionFile(String project_path, String formId, String project_id) throws Exception {
		//根据路径获取加载文件
		String formIdUpper = StringUtil.firstLetterToUpper(formId);//大写
		String formIdLower = StringUtil.firstLetterToLower(formId);//小写
		File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\"+project_id+"\\"+formId+"\\"+formIdUpper+"Action.java");
		//如果未找到文件
		if (!f.exists()) {
			if (!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
			//创建文件
			f.createNewFile();
			//创建输入流
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write("package com.futvan.z."+project_id+"."+formId+";\n");
			writer.write("import org.springframework.stereotype.Controller;\n");
			writer.write("import org.springframework.beans.factory.annotation.Autowired;\n");
			writer.write("import com.futvan.z.framework.core.SuperAction;\n");
			writer.write("import com.futvan.z."+project_id+"."+formId+"."+formIdUpper+"Service;\n");
			writer.write("@Controller\n");
			writer.write("public class "+formIdUpper+"Action extends SuperAction{\n");
			writer.write("	@Autowired\n");
			writer.write("	private "+formIdUpper+"Service "+formIdLower+"Service;\n");
			writer.write("}\n");
			writer.close();
			write.close();
		}
	}

	private void CreatePathFile(String project_path, String formId, String project_id) throws Exception {

		//创建JAVA源码路径
		String packPath = project_path+"\\src\\main\\java\\com\\futvan\\z\\"+project_id+"\\"+formId;
		FileUtil.mkdirs(packPath);

		//创建Web路径
		FileUtil.mkdirs(project_path+"\\src\\main\\webapp\\views\\"+project_id+"\\"+formId);
	}

	/**
	 * 	数据上移下移
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/MoveDownOrMoveUp")
	public ModelAndView MoveDownOrMoveUp(@RequestParam HashMap<String,String> bean) throws Exception {
		//从Session中获取用户与组织信息保存到Bean中
		GetSessionInfoToBean(bean,request);
		return commonService.MoveDownOrMoveUp(bean);
	}

	/**
	 *	系统状态监听 	
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/system_state")
	public ModelAndView system_state() throws Exception {
		ModelAndView model = new ModelAndView("common/system/system_state");
		HashMap info = new HashMap();
		//服务器参数
		info.put("system_state", JsonUtil.getJson(SystemUtil.getSystemState()));
		info.put("dbsMap", JsonUtil.getJson(z.dbsMap) );
		info.put("tables", JsonUtil.getJson(z.tables) );
		info.put("reports", JsonUtil.getJson(z.reports) );
		info.put("wf", JsonUtil.getJson(z.wf) );
		info.put("code", JsonUtil.getJson(z.code) );
		info.put("sp", JsonUtil.getJson(z.sp) );
		info.put("accesskey", JsonUtil.getJson(z.accesskey) );
		info.put("httpservices", JsonUtil.getJson(z.httpservices) );
		info.put("orgs", JsonUtil.getJson(z.orgs) );
		info.put("users", JsonUtil.getJson(z.users) );
		info.put("session_users", JsonUtil.getJson(z.session_users) );
		info.put("jobRunList", JsonUtil.getJson(z.jobRunList) );
		info.put("cms", JsonUtil.getJson(z.cms) );
		info.put("cmsColumn", JsonUtil.getJson(z.cmsColumnForNumber) );
		info.put("cmsList", JsonUtil.getJson(z.cmsList) );
		model.addObject("info", info);
		return model;
	}

	//	/**
	//	 * 	系统状态JSON
	//	 * @return
	//	 * @throws Exception
	//	 */
	//	@RequestMapping(value="/system_state_json")
	//	public @ResponseBody Result system_state_json() throws Exception {
	//		Result result = new Result();
	//		result.setCode(Code.SUCCESS);
	//		result.setMsg("system_state");
	//		HashMap info = new HashMap();
	//		info.put("system_state", SystemUtil.getSystemState());
	//		info.put("sp", JsonUtil.getJson(z.sp) );
	//		result.setData(info);
	//		return result;
	//	}

	/**
	 * 发短信验证码
	 * @param tel 手机
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/send_vcode")
	public @ResponseBody Result send_vcode(String name,String tel) throws Exception {
		Result result = new Result();
		if(z.isNotNull(tel)) {
			//判断当前tel是否已生成有效期内的code
			String code = "";
			List<HashMap<String,String>> vcodelist = sqlSession.selectList("select", "SELECT * FROM z_vcode WHERE  tel = '"+tel+"' AND endtime > NOW() order by endtime desc");
			if(vcodelist.size()>0) {
				code = vcodelist.get(0).get("vcode");
			}else {
				code = z.newZcode();
				z_vcode vc = new z_vcode();
				if(z.isNotNull(name)) {
					vc.setName(name);
				}
				vc.setZid(z.newZid("z_vcode"));
				vc.setVcode(code);
				vc.setTel(tel);
				vc.setEndtime(DateUtil.addMinute(DateUtil.getDateTime(), 5));//当前时间加5分钟
				int num = sqlSession.insert("z_vcode_insert", vc);
				if(num!=1) {
					z.Exception("创建并保存短信验证出错");
				}
			}
			result = SmsUtil.SendCodeSMS(tel, code);
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("手机号不能为空");
		}
		return result;
	}

	/**
	 * 导出Excel
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/export_excel")
	public ResponseEntity<byte[]> export_excel(@RequestParam HashMap<String,String> bean) throws Exception {
		String PageType = bean.get("PageType");
		if(z.isNotNull(PageType)) {
			//创建文件头信息
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", "export_"+DateUtil.getDateTime("yyyyMMddHHmm")+".xls");
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			//生成Excel文件流
			byte[] file = null;
			if("rlist".equals(PageType)) {
				file = commonService.getExportDataR(bean);
			}else if("list".equals(PageType)) {
				file = commonService.getExportData(bean);
			}
			//返回文件流
			return new ResponseEntity<byte[]>(file,headers, HttpStatus.CREATED);
		}else {
			z.Exception("PageType is null");
			return null;
		}
	}



	/**
	 * 删除文件
	 * @param tel 手机
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteFile")
	public @ResponseBody Result deleteFile(String url) throws Exception {
		Result result = new Result();
		if(z.isNotNull(url)) {
			Map<String,String> parameters = new HashMap<String, String>();
			String [] file_path = url.replace(z.sp.get("fileserverurl")+"/files/", "").split("/");
			if(z.isNotNull(file_path[0]) && z.isNotNull(file_path[1])) {
				parameters.put("path", file_path[0]);
				parameters.put("filename", file_path[1]);
				result = HttpUtil.doPostResult(z.sp.get("fileserverurl")+"/deleteServerFile", parameters);
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("非法文件路径|标准路径：xxxxxxxx/xx.扩展名");
			}

		}else {
			result.setCode(Code.ERROR);
			result.setMsg("url is null");
		}
		return result;
	}


	/**
	 * 删除服务器文件
	 * @param tel 手机
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteServerFile")
	public @ResponseBody Result deleteServerFile(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		String path = bean.get("path");
		String filename = bean.get("filename");
		if(z.isNotNull(path) && z.isNotNull(filename)) {
			String project_path = request.getServletContext().getRealPath("/")+"files\\";
			File f = new File(project_path+path+"\\"+filename);
			if (f.exists() && f.isFile()) {
				boolean b = f.delete();
				if(b) {
					//同时删除 z5 z1压缩版
					String[]filenameArray = filename.split("\\.");
					String fileName_z1 = filenameArray[0] +"_z1." + filenameArray[1];
					File f_z1 = new File(project_path+path+"\\"+fileName_z1);
					f_z1.delete();
					String fileName_z5 = filenameArray[0] +"_z5." + filenameArray[1];
					File f_z5 = new File(project_path+path+"\\"+fileName_z5);
					f_z5.delete();

					//删除成功后，判读文件夹是否为空，如果为空删文件夹
					String dirPath = project_path+path;
					if(FileUtil.dirsIsNull(dirPath)) {
						File dir = new File(dirPath);
						dir.delete();
					}

					result.setCode(Code.SUCCESS);
					result.setMsg("删除文件成功");
				}else{
					result.setCode(Code.ERROR);
					result.setMsg("删除文件失败|f.delete() return false");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到要删除的文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("path 和 filename 参数不可为空");
		}
		return result;
	}

	/**
	 * 重启Tomcat
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/RestartTomcat")
	public @ResponseBody Result RestartTomcat() throws Exception {
		Result result = new Result();
		if(SystemUtil.isEclipseRunTomcat()) {
			result.setCode(Code.ERROR);
			result.setMsg("开发环境中，请手动重启Tomcat");
		}else {
			//运行DOC命令-运行重启Tomcat脚本
			SystemUtil.dos("cmd /c "+SystemUtil.getRunClassPath()+"\\RestartTomcat.bat");
			
			result.setCode(Code.SUCCESS);
			result.setMsg("正在重启中，请稍后刷新页面");
		}
		
		return result;
	}
}